package com.csit.util;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import org.apache.commons.betwixt.io.BeanReader;
import org.apache.commons.betwixt.io.BeanWriter;
import org.xml.sax.SAXException;

/**
 * 
 * @Description: XML和JavaBean进行相互转换的工具类
 * @Copyright: 福州骏华信息有限公司 (c)2012
 * @Created Date : 2012-7-18
 * @author longweier
 * @vesion 1.0
 */
public class XmlAndBeanUtil {
	
	/**
	 * 
	 * @Description: XML转换成JavaBean
	 * @param
	 * @Create: 2012-7-18 上午10:48:02
	 * @author longweier
	 * @update logs
	 * @param xmlString xml文件路径
	 * @param clazz     需要转换的JavaBean
	 * @return
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Object xmlToObject(String xmlString,Class clazz){
		Object object = null;
		//创建一个读取xml文件的io流
		StringReader xmlReader = new StringReader(xmlString);
		//创建一个BeanReader实例，相当于转换器
		BeanReader beanReader = new BeanReader();
		//配置BeanReader实例
		beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
		beanReader.getBindingConfiguration().setMapIDs(false);
		//注册要转换对象的类，并且知道跟节点名称
		try {
			beanReader.registerBeanClass(clazz);
			object = beanReader.parse(xmlReader);
		} catch (IntrospectionException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} finally{
			xmlReader.close();
		}
		
		return object;
	}
	
	/**
	 * 
	 * @Description: JavaBean转换成XML
	 * @param
	 * @Create: 2012-7-18 上午11:06:18
	 * @author longweier
	 * @update logs
	 * @param object 需要转换的JavaBean
	 * @return
	 * @return
	 * @throws Exception
	 */
	public static String objectToXml(Object object){
		String xml = null;
		//创建一个输出流，建用来输出Java转换的XML文件
		StringWriter outputWriter = new StringWriter();
		//输出XML的文件头
		outputWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
		//创建一个BeanWriter实例,并将BeanWriter的输出重定向到指定的输出流
		BeanWriter beanWriter = new BeanWriter(outputWriter);
		//配置BeanWriter对象
		beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
		beanWriter.getBindingConfiguration().setMapIDs(false);
		beanWriter.setWriteEmptyElements(false);
		try {
			beanWriter.write(object);
			xml = outputWriter.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IntrospectionException e) {
			e.printStackTrace();
		} finally{
			try {
				outputWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return  xml;
	}
}
